package bma.common.thriftboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import bma.common.thrift.ThriftServer;

public class ThriftBoot {
	
	static final String THRIFT_SERVER_XML = "classpath:thrift_server.xml";
	static final String THRIFT_DEFAULT_SERVER = "server";
	
	private static Logger logger = LoggerFactory.getLogger(ThriftBoot.class);
	
	public static void main(String[] args){
		if (logger.isDebugEnabled()){
			logger.debug("Start to boot thrift services...");
		}
		
		String thriftServerXml = THRIFT_SERVER_XML;
		try{
			if(!System.getProperty("thrift_server_xml").isEmpty()){
				thriftServerXml = System.getProperty("thrift_server_xml"); 
			}
		}catch (NullPointerException e) {
			if (logger.isDebugEnabled()) logger.debug("not specify thrift_server_xml...");
		}
		
		String thriftServer = THRIFT_DEFAULT_SERVER;
		try{
			if(!System.getProperty("thrift_server").isEmpty()){
				thriftServer = System.getProperty("thrift_server");
			}
		}catch (NullPointerException e) {
			if (logger.isDebugEnabled()) logger.debug("not specify thrift_default_server...");
		}
		
    	ThriftBoot thriftBoot = new ThriftBoot();
    	
    	try {
    		thriftBoot.boot(thriftServerXml,thriftServer);
		} catch (Exception e) {
			System.out.println("xml=>"+thriftServerXml+"  server=>"+thriftServer+"  exception=>"+e.getMessage());
			if (logger.isDebugEnabled()){
				logger.debug(e.getMessage()+"\n" + e.getStackTrace());
			}
		}
	}
	
	public void boot(String thriftServerXml, String server ) throws Exception {
		
		if(thriftServerXml.isEmpty()){
			throw new Exception("thriftServerXml is miss!!");
		}
		
		if(server.isEmpty()){
			throw new Exception("please specify server!!");
		}
		
		FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(thriftServerXml);
		ThriftServer thriftServer = context.getBean(server, ThriftServer.class);
		
		if (logger.isDebugEnabled()){
			logger.debug(thriftServer.toString());
		}

		//启动
		thriftServer.start();
		
		//监听
		final Thread t = Thread.currentThread();
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				t.interrupt();
			}
		});
		try {
			Thread.sleep(Long.MAX_VALUE);
		} catch (InterruptedException e) {
			logger.debug("Interrupted!");
		}
		
	}

}
